#-*- coding: utf-8 -*-
# stino/language.py

import os
import re

from . import constant
from . import fileutil
from . import textutil

class LanguageItem:
	def __init__(self):
		self.name = ''
		self.en_name = ''
		self.country = ''
		self.file_name = ''
		self.file = ''
	
	def setName(self, name):
		self.name = name

	def setEnName(self, en_name):
		self.en_name = en_name

	def setCountry(self, country):
		self.country = country

	def setFileName(self, file_name):
		self.file_name = file_name

	def setFile(self, lang_file):
		self.file = lang_file

	def getName(self):
		return self.name

	def getEnName(self):
		return self.en_name

	def getCountry(self):
		return self.country

	def getFileName(self):
		return self.file_name

	def getFile(self):
		return self.file

	def getCaption(self):
		if self.country:
			caption = '%s (%s)-%s' % (self.name, self.en_name, self.country)
		else:
			caption = '%s (%s)' % (self.name, self.en_name)
		return caption

class Language:
	def __init__(self):
		self.total_language_filename_list = []
		self.total_language_item_list = []
		self.language_item_list = []
		self.trans_dict = {}
		self.genLanguageItemList()
		self.setDefaultLanguage()
		self.genDefaultTransDict()
		self.genDefaultLangFile()
		self.refresh()

	def refresh(self):
		self.genTransDict()

	def genTotalLanguageItemList(self):
		iso_file = os.path.join(constant.config_root, 'ISO639_1')
		# opened_file = open(iso_file, 'r', encoding='utf-8')
		# lines = opened_file.readlines()
		# opened_file.close()
		lines = fileutil.readFileLines(iso_file)
		for line in lines:
			line = line.strip()
			if line:
				info_list = line.split('=')
				file_name = info_list[0].strip()
				en_name = info_list[1].strip()
				name = info_list[2].strip()
				lang_item = LanguageItem()
				lang_item.setName(name)
				lang_item.setEnName(en_name)
				lang_item.setFileName(file_name)
				self.total_language_item_list.append(lang_item)
				self.total_language_filename_list.append(file_name)

	def getLanguageItemList(self):
		return self.language_item_list

	def genLanguageItemList(self):
		self.genTotalLanguageItemList()
		lang_file_name_list = fileutil.listDir(constant.language_root, with_dirs = False)
		for lang_file_name in lang_file_name_list:
			if lang_file_name in self.total_language_filename_list:
				lang_file = os.path.join(constant.language_root, lang_file_name)
				index = self.total_language_filename_list.index(lang_file_name)
				lang_item = self.total_language_item_list[index]
				lang_item.setFile(lang_file)
				self.language_item_list.append(lang_item)

	def setDefaultLanguage(self):
		chosen_language = constant.global_settings.get('language', -1)
		if chosen_language > -1:
			if chosen_language < len(self.language_item_list):
				return

		for lang_item in self.language_item_list:
			file_name = lang_item.getFileName()
			if file_name == constant.sys_language:
				index = self.language_item_list.index(lang_item)
				constant.global_settings.set('language', index)
				break

	def genDefaultTransDict(self):
		pattern_text = r"translate\('([\S\s]+?)'"
		pattern = re.compile(pattern_text)

		self.trans_dict = {}
		py_starter_file = os.path.join(constant.stino_root, 'StinoStarter.py')
		py_menu_file = os.path.join(constant.app_root, 'menu.py')
		py_file_list = [py_starter_file, py_menu_file]
		for py_file in py_file_list:
			# opened_file = open(py_file, 'r')
			# text = opened_file.read()
			# opened_file.close()
			text = fileutil.readFile(py_file)
			trans_str_list = pattern.findall(text)
			for trans_str in trans_str_list:
				self.trans_dict[trans_str] = trans_str

	def genTransDict(self):
		chosen_language = constant.global_settings.get('language', -1)
		if chosen_language > -1:
			if chosen_language < len(self.language_item_list):
				language_item = self.language_item_list[chosen_language]
				lang_file = language_item.getFile()
				# opened_file = open(lang_file, 'r', encoding='utf-8')
				# lines = opened_file.readlines()
				# opened_file.close()
				lines = fileutil.readFileLines(lang_file)

				block_list = textutil.getBlockList(lines, sep = 'msgid')
				for block in block_list:
					if block:
						for line in block:
							index = line.index('"')
							cur_str = line[index+1:]
							cur_str = cur_str[:-1]
							if 'msgid' in line:
								key = cur_str
							elif 'msgstr' in line:
								value = cur_str
						self.trans_dict[key] = value

	def genDefaultLangFile(self):
		lang_file = os.path.join(constant.language_root, 'default')

		text = '# This file was auto generated. Do not edit this file.\n\n'
		text += '# LANGUAGE: {language} ({language})\n'
		text += '# {language} translations for Stino Plugin.\n'
		text += '# Copyright (C) 2012-2013 Robot-Will\n'
		text += '# This file is distributed under the same license as the Stino Plugin.\n'
		text += '# {translator} {EMAIL@ADDRESS}\n'
		text += '#\n\n'
		for trans_str in self.trans_dict:
			text += 'msgid "%s"\n' % trans_str
			text += 'msgstr "%s"\n\n' % trans_str

		# opened_file = open(lang_file, 'w')
		# opened_file.write(text)
		# opened_file.close()
		fileutil.writeFile(lang_file, text)

	def translate(self, text, para_list = []):
		if text in self.trans_dict:
			text = self.trans_dict[text]
		for para in para_list:
			index = para_list.index(para)
			replaced_text = '{%d}' % index
			text = text.replace(replaced_text, para)
		return text